from django import forms
from django.core.validators import ValidationError
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect, reverse
from django.conf import settings
from django.core.validators import RegexValidator

from web import models
from web.utils.bootstrap import BootstrapForm
from web.utils.encrypt import md5
from web.utils.group import Option, get_search_group_condition
from web.utils.link import filter_reverse
from web.utils.pager import Pagernation
from web.utils.response import BaseResponse


def users_list(request):
    """用户列表"""

    # 配置组合搜索
    search_group = [
        Option('role'),
    ]
    model_class = models.Users
    search_group_list = []
    for option_object in search_group:
        search_group_list.append(option_object.get_queryset_or_tuple(request, model_class))
    # 获取组合搜索条件
    conn = get_search_group_condition(search_group, request)

    # 获取模糊查询条件
    search_list = [
        "username__contains",
        "nickname__contains"
    ]
    keyword = request.GET.get("keyword", "").strip()
    con = Q()
    con.connector = "OR"
    if keyword:
        for item in search_list:
            con.children.append((item, keyword))

    # 获取所有数据
    queryset = models.Users.objects.filter(con).filter(**conn).filter(active=1)

    pager = Pagernation(request, queryset)

    context = {
        'pager': pager,
        'keyword': keyword,
        'search_group_row_list': search_group_list
    }

    return render(request, 'user_list.html', context)


class UsersModelForm(BootstrapForm, forms.ModelForm):
    exclude_field_list = ['role']
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput,
        validators=[RegexValidator(regex=r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\s\S]{8,}$',
                                   message='密码必须包含大小写、字母和数字，长度至少8位')])
    confirm_password = forms.CharField(
        label="重复密码",
        widget=forms.PasswordInput
    )

    class Meta:
        model = models.Users
        fields = ['username', 'nickname', 'password', 'confirm_password', 'role']
        widgets = {
            'password': forms.PasswordInput,
            'role': forms.RadioSelect(attrs={'class': 'form-radio'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['role'].choices = ((1, '管理员'), (2, '安全运营'), (3, '普通用户'))

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if models.Users.objects.filter(username=username).exists():
            raise ValidationError('用户名重复，请重新输入')
        return username

    def clean_password(self):
        password = self.cleaned_data.get('password')
        return md5(password)

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = md5(self.cleaned_data.get('confirm_password', ''))
        if password != confirm_password:
            raise ValidationError('两次密码输入不一致，请重新输入!')
        return confirm_password


def users_add(request):
    if request.method == 'GET':
        form = UsersModelForm()
        return render(request, 'form2.html', {'form': form})

    form = UsersModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})

    form.save()
    return redirect(reverse('users_list'))


class UsersEditModelForm(BootstrapForm, forms.ModelForm):
    exclude_field_list = ['role']

    class Meta:
        model = models.Users
        fields = ['username', 'nickname', 'role']
        widgets = {
            'role': forms.RadioSelect(attrs={'class': 'form-radio'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['role'].choices = ((1, '管理员'), (2, '安全运营'), (3, '普通用户'))


def users_edit(request, pk):
    instance = models.Users.objects.filter(id=pk, active=1).first()

    if request.method == 'GET':
        form = UsersEditModelForm(instance=instance)
        return render(request, 'form2.html', {'form': form})

    form = UsersEditModelForm(data=request.POST, instance=instance)
    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})

    form.save()
    return redirect(filter_reverse(request, '/users/list/'))


class UsersResetModelform(BootstrapForm, forms.ModelForm):
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput,
        validators=[RegexValidator(regex=r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\s\S]{8,}$',
                                   message='密码必须包含大小写、字母和数字，长度至少8位')])
    confirm_password = forms.CharField(
        label="重复密码",
        widget=forms.PasswordInput
    )

    class Meta:
        model = models.Users
        fields = ['password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput
        }

    def clean_password(self):
        password = self.cleaned_data.get('password')
        return md5(password)

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = md5(self.cleaned_data.get('confirm_password', ''))
        if password != confirm_password:
            raise ValidationError('两次密码输入不一致，请重新输入!')
        return confirm_password


def users_reset(request, pk):
    if request.method == 'GET':
        form = UsersResetModelform()
        return render(request, 'form2.html', {'form': form})

    instance = models.Users.objects.filter(id=pk, active=1).first()
    form = UsersResetModelform(data=request.POST, instance=instance)
    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})
    form.save()
    return redirect(reverse('users_list'))


def users_delete(request):
    cid = request.GET.get('cid', 0)
    if not cid:
        res = BaseResponse(status=False, detail='请选择要删除的数据')
        return JsonResponse(res.dict)

    exists = models.Users.objects.filter(id=cid, active=1).exists()
    if not exists:
        res = BaseResponse(status=False, detail="要删除的数据不存在")
        return JsonResponse(res.dict)
    models.Users.objects.filter(id=cid, active=1).update(active=0)
    res = BaseResponse(status=True)
    return JsonResponse(res.dict)


class CurrentUserInfoChangeForm(BootstrapForm, forms.Form):
    nickname = forms.CharField(label='姓名', required=True)
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput,
        validators=[RegexValidator(regex=r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\s\S]{8,}$',
                                   message='密码必须包含大小写、字母和数字，长度至少8位')])
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput, required=True)

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password != confirm_password:
            raise ValidationError('两次密码输入不一致,请重新输入')
        return confirm_password


def current_userinfo_change(request):
    current_user_id = request.session.get(settings.MOBILEDJ_SESSION_KEY)['id']
    user_obj = models.Users.objects.filter(id=current_user_id).first()
    if request.method == 'GET':
        form = CurrentUserInfoChangeForm(initial={'nickname': user_obj.nickname})
        return render(request, 'form.html', {'form': form})
    form = CurrentUserInfoChangeForm(data=request.POST)
    if form.is_valid():
        password = form.cleaned_data['password']
        nickname = form.cleaned_data['nickname']
        user_obj.nickname = nickname
        user_obj.password = md5(password)
        user_obj.save()
        return redirect(filter_reverse(request, '/users/list/'))
    return render(request, 'form.html', {'form': form})
